package org.springframework.security.oauth2.provider.endpoint;

import java.security.Principal;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@FrameworkEndpoint
public class TokenKeyEndpoint {

    protected final Log logger = LogFactory.getLog(getClass());

    private JwtAccessTokenConverter converter;

    public TokenKeyEndpoint(JwtAccessTokenConverter converter) {
        super();
        this.converter = converter;
    }

    /**
     * localhost:8082/auth/oauth/token_key
     * 主要是经过 BasicAuthenticationFilter 过滤
     */
    @RequestMapping(value = "/oauth/token_key", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getKey(Principal principal) {
        if ((principal == null || principal instanceof AnonymousAuthenticationToken) && !converter.isPublic()) {
            throw new AccessDeniedException("You need to authenticate to see a shared key");
        }
        return converter.getKey();
    }
}
